var crypto = require('crypto');
var  client = require('../database');
mysql = client.getDbCon();

exports.login = function(req,res){
    console.log('进入登陆页面')
    var uname = req.body.uname;
    var upassword = req.body.upassword;

    var md5 = crypto.createHash('md5');
    md5.update(upassword);
    var pwd = md5.digest('hex');

    var selectNameSQL = "select count(name) nub from tb_userinfo where name= '" + uname +"' and password='" + pwd + "'";

    mysql.query(selectNameSQL,function(err,rows){
        if (err) console.log(err);
        console.log("SELECT ==> ");
        console.log(rows);

        for(var i in rows){
            console.log("---------" + rows[i].nub);
            var val = rows[i].nub;
            if(val ==1){
                req.session.user = uname;
               return res.redirect('/toMainPage');
            }if(val ==0){
                req.session.user = "";
                return res.redirect('/');
            }
        }
    });
};

exports.validateUser = function(req,res){
    var uname = req.body.username;
    console.log("uname--" + uname);
    var selectNameSQL = "select name from tb_userinfo where name= '" + uname +"'";

    mysql.query(selectNameSQL,function(err,rows){
        if (err) console.log(err);
        console.log("SELECT ==> ");
        console.log(rows);
        res.writeHead(200,{"Content-Type":"text/plain"});
        res.end(JSON.stringify(rows));
    });
};

exports.executeRegister = function(req, res){
    var name = req.body.uname;
    var password = req.body.password;
    var phone = req.body.phone;
    var email = req.body.email;
    var u_type = 0;

    var md5 = crypto.createHash('md5');
    md5.update(password);
    var pwd = md5.digest('hex');

   var insertSQL = 'insert into tb_userinfo values(null,' +'"'+ name +'"' +',' + '"'+pwd+'"' +',' + '"'+phone+'"' +',' +'"'+email+'"'+',' + '"'+ u_type +'"' +') ';

    mysql.query(insertSQL,function(err,rows){
        if (err) console.log(err);
        console.log("INSERT ==> ");
        console.log(rows);
        res.redirect('/');
    });
};